import 'package:flutter/material.dart';
import 'package:osc/common/constants.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_open_source_company_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/common_page.dart';
import 'package:osc/ui/pages/project/project_list_fragment.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class OpenSourceCompanyPage extends StatefulWidget {

  @override
  _OpenSourceCompanyPageState createState() => _OpenSourceCompanyPageState();
}

class _OpenSourceCompanyPageState extends State<OpenSourceCompanyPage> {

  HttpRepository httpRepository;
  int page = 0;
  int size = 0;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscOpenSourceCompany> list;

  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollPhysics scrollPhysics = ScrollPhysics();


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: "开源公司",
        body: SmartRefresher(
            controller: controller,
//          enablePullUp: false,
          onRefresh: refresh,
//          onLoading: loadMore,
          child: buildGrid(),
        ),
    );
  }

  buildGrid(){
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
          mainAxisSpacing: Dimens.gap_activity_horizontal,
          crossAxisSpacing: Dimens.gap_activity_horizontal,
        ),
        itemBuilder: (BuildContext context, int index){
          return buildGridItem(list.elementAt(index));
        },
        itemCount: size,
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_activity_vertical),
    );
  }

  buildGridItem(OscOpenSourceCompany company){
    return GestureDetector(
      onTap: (){
        jumpToPageForResult(CommonPage(title: "${company.name}开源软件", body: ProjectListFragment(catalog: 4, companyId: company.id,),));
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(Dimens.view_radius_size_small),
        ),
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_smallest, vertical: Dimens.gap_view_big),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_big),
                child: ImageLoader(url: company.logo, fit: BoxFit.contain,),
              ),
              flex: 4,
            ),
            Expanded(
              flex: 5,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_small),
                      child: SmallWidgets.buildText(company.name, Colors.black, Dimens.font_sp12, fontWeight: FontWeight.bold),
                    ),
                    SmallWidgets.buildText("开源软件数 ${company.projectCount}", Colors.black54, Dimens.font_sp12),
                  ],
                ),
            ),
          ],
        ),
      ),
    );
  }

  refresh() async{
    page = 1;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    List<OscOpenSourceCompany> tempList;
    int tempSize = 0;
    await httpRepository.getOpenSourceCompanyList().then((resp){
      if(resp != null && resp.success){
        OscOpenSourceCompanyEntity entity = resp.result;
        if(entity != null){
          tempList = entity.data;
        }
      }
    });
    tempSize = tempList?.length??0;
    if(page == 1){
      list = tempList;
    } else {
      list.addAll(tempList);
    }
    size = list?.length??0;
    if(tempSize == Constant.PAGE_SIZE){
      page++;
    }
    if(mounted) {
      setState(() {
        controller.loadComplete();
        controller.refreshCompleted();
      });
    }
  }


  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
